package com.qianfeng.openapi.search.service.impl;

import com.qianfeng.openapi.common.enums.OpenApiEnums;
import com.qianfeng.openapi.common.exception.OpenApiEx;
import com.qianfeng.openapi.search.bean.LayUITableVO;
import com.qianfeng.openapi.search.service.ElasticsearchService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class ElasticsearchServiceImpl implements ElasticsearchService {


    @Autowired
    private RestHighLevelClient client;


    @Override
    public void addDocument(String index, String id, String json) throws IOException {
        //1. req
        IndexRequest request = new IndexRequest(index);
        request.id(id);

        //2. 封
        request.source(json, XContentType.JSON);

        //3. 发
        IndexResponse resp = client.index(request, RequestOptions.DEFAULT);

        //4. 判
        if(!resp.getResult().toString().equalsIgnoreCase("created")){
            log.info("【Elasticsearch添加操作】 添加文档失败!! result = {}",resp.getResult().toString());
            throw new OpenApiEx(OpenApiEnums.ELASTICSEARCH_ADD_ERROR);
        }
    }
    @Override
    public LayUITableVO searchAdminUserDocument(String index_name, Map<String, Object> parameters) throws IOException {
        //1. req
        SearchRequest request = new SearchRequest();
        request.indices(index_name);
        //2. 封
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();


        //2.1 查询条件
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        //2.1.1 realName
        String realName = (String) parameters.get("realName");
        if(!StringUtils.isEmpty(realName)){
            boolQueryBuilder.must(QueryBuilders.matchQuery("realName",realName));
        }
        //2.1.2 email
        String email = (String) parameters.get("email");
        if(!StringUtils.isEmpty(email)){
            boolQueryBuilder.must(QueryBuilders.matchQuery("email",email));
        }
        //2.1.3 status
        Integer status = (Integer) parameters.get("status");
        if(status != null){
            boolQueryBuilder.must(QueryBuilders.termQuery("status",status));
        }
        sourceBuilder.query(boolQueryBuilder);

        // MySQL -> limit 起始索引 查询条数
        //2.2 分页信息
        Integer page = (Integer) parameters.get("page");
        Integer limit = (Integer) parameters.get("limit");
        sourceBuilder.from((page - 1) * limit);
        sourceBuilder.size(limit);

        //2.3 高亮显示
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.fragmentSize(50);
        highlightBuilder.preTags("<span style='color:red;'>");
        highlightBuilder.postTags("</span>");
        highlightBuilder.field("realName").field("email");
        sourceBuilder.highlighter(highlightBuilder);

        request.source(sourceBuilder);

        //3. 发
        SearchResponse resp = client.search(request, RequestOptions.DEFAULT);

        //4. 封
        LayUITableVO vo = new LayUITableVO();
        //4.1 封装count
        vo.setCount(resp.getHits().getTotalHits().value);
        //4.2 封装data
        List<Map> data = new ArrayList<>();
        for (SearchHit hit : resp.getHits().getHits()) {
            Map<String, Object> map = hit.getSourceAsMap();
            if(!StringUtils.isEmpty(realName)) {
                // 将realName作为了查询条件,有高亮显示的数据返回
                HighlightField realNameField = hit.getHighlightFields().get("realName");
                map.put("realName",realNameField.fragments()[0].toString());
            }
            if(!StringUtils.isEmpty(email)) {
                // 将realName作为了查询条件,有高亮显示的数据返回
                HighlightField emailField = hit.getHighlightFields().get("email");
                map.put("email",emailField.fragments()[0].toString());
            }
            data.add(map);
        }
        vo.setData(data);

        //5. 返回vo
        return vo;
    }

}
